<template>
    <div style="width: 95%;margin: auto;">
        <!-- 
        :inline :把el-form-item 设置 行内元素
         -->
        <el-form :inline="true" :model="ordersFrom" class="demo-form-inline">
            <el-form-item style="width: 180px;">
                <el-select v-model="ordersFrom.status" placeholder="订单状态" clearable>
                    <el-option label="未审批" value="0" />
                    <el-option label="未通过" value="1" />
                    <el-option label="已通过" value="2" />
                    <el-option label="已归还" value="3" />
                </el-select>
            </el-form-item>
            <el-form-item label-width="180px">
                <el-input v-model.number="ordersFrom.totalAmount" placeholder="总金额≥" style="width: 180px" clearable
                    type="number" step="0.01" />
            </el-form-item>
            <el-form-item>
                <el-date-picker v-model="ordersFrom.startDate" type="date" placeholder="起租时间" clearable />
            </el-form-item>
            <el-form-item>
                <el-date-picker v-model="ordersFrom.endDate" type="date" placeholder="归还时间" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="clickfindAll(1)" style="width: 100px;">查询</el-button>
            </el-form-item>
        </el-form>
    </div>


    <div style="margin-bottom: 10px;">
        <span style="width: 95%;margin-left: 35px;">
            <el-button type="primary" @click="batchApproval()">批量通过</el-button>
        </span>
        <span style="width: 95%;margin-left: 10px;">
            <el-button type="primary" @click="batchRejection()">批量打回</el-button>
        </span>
    </div>


    <el-table :data="ordersPage.allorders" border style="width: 95%; margin: auto;"
        @selection-change="handleSelectionChange" :default-sort="{ prop: 'createtime', order: 'descending' }"
        ref="elTableRef">
        <!-- 添加复选框选项 -->
        <el-table-column type="selection" width="55" />
        <el-table-column label="订单编号" prop="oid" width="100px" fixed />
        <el-table-column label="用户名" prop="user.username" width="100px" />
        <el-table-column label="用户类型" width="150px">
            <!-- 插槽 -->
            <template #default="scope">
                <el-tag v-if="scope.row.user.type == '管理员'" type="danger">管理员</el-tag>
                <el-tag v-else-if="scope.row.user.type == 'svip'" type="danger">svip</el-tag>
                <el-tag v-else type="primary">普通用户</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="汽车名" prop="car.cname" width="150px" />
        <el-table-column label="起租时间" prop="startDate" width="150px" />
        <el-table-column label="归还时间" prop="endDate" width="150px" />
        <el-table-column label="总金额" prop="totalAmount" width="100px" />
        <el-table-column label="订单状态" prop="status" width="150px">
            <template #default="scope">
                <el-tag v-if="scope.row.status == 0" type="primary">未审批</el-tag>
                <el-tag v-else-if="scope.row.status == 1" type="danger">未通过</el-tag>
                <el-tag v-else-if="scope.row.status == 2" type="success">已通过</el-tag>
                <el-tag v-else type="info">已归还</el-tag>
            </template>
        </el-table-column>
        <el-table-column width="200px" fixed="right" label="操作">
            <template #default="scope">
                <div style="display:flex;gap:8px;align-items:center">
                    <!-- 1. 查看 -->
                    <div style="width:32px;height:32px;display:inline-flex;align-items:center;justify-content:center">
                        <el-tooltip effect="dark" content="查看订单详情" placement="bottom">
                            <el-button type="primary" :icon="Search" circle @click="handleEdit(scope.row)" />
                        </el-tooltip>
                    </div>

                    <!-- 2. 还车坑位 -->
                    <div style="width:32px;height:32px;display:inline-flex;align-items:center;justify-content:center">
                        <el-tooltip v-if="scope.row.status == 2" effect="dark" content="还车" placement="bottom">
                            <el-button type="warning" :icon="CircleCheck" circle @click="doReturn(scope.row)" />
                        </el-tooltip>
                        <!-- 按钮隐藏时，用同尺寸空盒子占坑 -->
                        <div v-else style="width:32px;height:32px;background:transparent" />
                    </div>

                    <!-- 3. 打回 -->
                    <div style="width:32px;height:32px;display:inline-flex;align-items:center;justify-content:center">
                        <el-tooltip v-if="scope.row.status !== 3" effect="dark" content="打回" placement="bottom">
                            <el-button type="danger" :icon="CircleCloseFilled" circle @click="doReject(scope.row)" />
                        </el-tooltip>
                        <!-- 已归还占位坑 -->
                        <div v-else style="width:32px;height:32px;background:transparent" />
                    </div>

                    <!-- 4. 通过 -->
                    <div style="width:32px;height:32px;display:inline-flex;align-items:center;justify-content:center">
                        <el-tooltip v-if="scope.row.status !== 3" effect="dark" content="通过" placement="bottom">
                            <el-button type="success" :icon="SuccessFilled" circle @click="doApprove(scope.row)" />
                        </el-tooltip>
                        <!-- 已归还占位坑 -->
                        <div v-else style="width:32px;height:32px;background:transparent" />
                    </div>
                </div>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页插件 -->
    <div style="width: 95%;margin: 10px auto;">
        <el-pagination background layout="prev, pager, next" v-model:page-size="ordersFrom.pageSize"
            v-model:current-page="ordersFrom.pageNum" :total="ordersFrom.total" @current-change="findAll" />
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog title="订单详情" v-model="detailVisible" width="520px" :close-on-click-modal="false"
        style="--el-dialog-margin-top: 10vh;">
        <div style="font-size: 14px; line-height: 26px; color: #303133;">
            <!-- 第一行：头像 + 用户 -->
            <div style="display: flex; align-items: center; margin-bottom: 12px;">
                <img :src="detail.user?.imgPath || 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'"
                    style="width: 60px; height: 60px; border-radius: 50%; object-fit: cover; margin-right: 12px;" />
                <div>
                    <div>
                        <span style="font-weight: bold;">用户名：</span>
                        <span>{{ detail.user?.username }}</span>
                    </div>
                    <div>
                        <span style="font-weight: bold;">用户类型：</span>
                        <el-tag v-if="detail.user?.type === '管理员'" type="danger"
                            style="height: 22px; line-height: 22px; padding: 0 5px;">管理员</el-tag>
                        <el-tag v-else-if="detail.user?.type === 'svip'" type="danger"
                            style="height: 22px; line-height: 22px; padding: 0 5px;">svip</el-tag>
                        <el-tag v-else type="primary"
                            style="height: 22px; line-height: 22px; padding: 0 5px;">普通用户</el-tag>
                    </div>
                </div>
            </div>
            <hr>
            </hr>

            <!-- 汽车图片 + 信息 -->
            <div style="display: flex; align-items: center; margin-bottom: 12px;">
                <img :src="detail.car?.photo || 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'"
                    style="width: 100px; height: 70px; object-fit: cover; border-radius: 4px; margin-right: 12px;" />
                <div>
                    <div>
                        <span style="font-weight: bold;">汽车名：</span>
                        <span>{{ detail.car?.cname }}</span>
                    </div>
                    <div>
                        <span style="font-weight: bold;">品牌/型号：</span>
                        <span>{{ detail.car?.brand }} / {{ detail.car?.model }}</span>
                    </div>
                    <div>
                        <span style="font-weight: bold;">当日租价：</span>
                        <span style="color: #f56c6c;">¥{{ detail.dailyRate }}</span>
                    </div>
                </div>
            </div>

            <!-- 其余字段 -->
            <div style="margin-bottom: 8px;">
                <span style="display:inline-block;width: 100px;font-weight:bold;">订单编号：</span>
                <span>{{ detail.oid }}</span>
            </div>
            <div style="margin-bottom: 8px;">
                <span style="display:inline-block;width: 100px;font-weight:bold;">起租时间：</span>
                <span>{{ detail.startDate }}</span>
            </div>
            <div style="margin-bottom: 8px;">
                <span style="display:inline-block;width: 100px;font-weight:bold;">归还时间：</span>
                <span>{{ detail.endDate }}</span>
            </div>
            <div style="margin-bottom: 8px;">
                <span style="display:inline-block;width: 100px;font-weight:bold;">总金额：</span>
                <span style="color: #f56c6c; font-weight: bold;">¥{{ detail.totalAmount }}</span>
            </div>
            <div>
                <span style="display:inline-block;width: 100px;font-weight:bold;">订单状态：</span>
                <el-tag v-if="detail.status === 0" type="primary"
                    style="height: 22px; line-height: 22px; padding: 0 5px;">未审批</el-tag>
                <el-tag v-else-if="detail.status === 1" type="danger"
                    style="height: 22px; line-height: 22px; padding: 0 5px;">未通过</el-tag>
                <el-tag v-else-if="detail.status === 2" type="success"
                    style="height: 22px; line-height: 22px; padding: 0 5px;">已通过</el-tag>
                <el-tag v-else-if="detail.status === 3" type="info"
                    style="height: 22px; line-height: 22px; padding: 0 5px;">已归还</el-tag>
            </div>
        </div>

        <!-- 底部按钮 -->
        <template #footer>
            <span>
                <el-button type="primary" @click="detailVisible = false" style="width: 80px;">关 闭</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
//1.引入ref和reactive
import { ref, reactive, onMounted } from 'vue';
import request from '../utils/request';
import { Delete, Edit, Plus, Search, Setting, SuccessFilled, CircleCloseFilled, CircleCheck } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
//日期格式化工具
const formatDate = (date) => {
    if (!date) return null;
    const d = new Date(date);
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${y}-${m}-${day}`;
};

/* 弹窗开关 & 临时数据 */
const detailVisible = ref(false)
const detail = reactive({})

/* 打开弹窗：把行数据一次性拷进去 */
const handleEdit = (row) => {
    Object.assign(detail, row)   // row 里已包含 user、car
    detailVisible.value = true
}
//存放后端查询用户数据变量
let ordersPage = reactive({
    allorders: [],

})
//声明一个对象，用于条件查询
let ordersFrom = ref({
    pageNum: 0,
    pageSize: 5,
    total: 0
})



// ------------------------------------打回，通过，批量打回，批量通过,还车----------------------------------------
/* 1. 当前被选中的行 */
const multipleSelection = ref([])

/* 2. selection-change 事件 */
const handleSelectionChange = (rows) => {
    multipleSelection.value = rows.map(r => r.oid)
}

/* 3. 单行通过 / 打回 */
const doApprove = async (row) => {
    await toggleStatus([row.oid], '/orders/approve', '已通过')
}
const doReject = async (row) => {
    await toggleStatus([row.oid], '/orders/reject', '已打回')
}

/* 4. 批量通过 / 打回 */
const batchApproval = async () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请先勾选订单')
        return
    }
    await toggleStatus(multipleSelection.value, '/orders/batchApprove', '批量通过成功')
}
const batchRejection = async () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请先勾选订单')
        return
    }
    await toggleStatus(multipleSelection.value, '/orders/batchReject', '批量打回成功')
}

/* 5. 通用切换状态函数 */
const toggleStatus = async (oids, url, msg) => {
    try {
        const res = await request.post(url, oids.length === 1 ? { id: oids[0] } : { ids: oids })
        if (res.data.success) {
            ElMessage.success(msg)
            // 刷新当前页
            await findAll(ordersFrom.value.pageNum)
        } else {
            ElMessage.error(res.data.message || '操作失败')
        }
    } catch (e) {
        ElMessage.error('网络错误')
    }
}

/* ----------------- 还车业务 ----------------- */
const doReturn = async (row) => {
    try {
        const res = await request.post('/orders/returnCar', { id: row.oid })
        if (res.data.success) {
            ElMessage.success('还车成功')
            await findAll(ordersFrom.value.pageNum) // 刷新当前页
        } else {
            ElMessage.error(res.data.message || '还车失败')
        }
    } catch {
        ElMessage.error('网络错误')
    }
}
// ------------------------------------打回，通过，批量打回，批量通过----------------------------------------



//条件查询所有方法
const findAll = async (currentpage) => {
    ordersFrom.value.pageNum = currentpage;

    // 把 Date 转成字符串再传后端
    const params = {
        ...ordersFrom.value,
        startDate: formatDate(ordersFrom.value.startDate),
        endDate: formatDate(ordersFrom.value.endDate),
    };

    let res = await request.post("/orders/queryCondition", params);

    if (res.data.success) {
        ordersPage.allorders = res.data.data.list;
        ordersFrom.value.total = res.data.data.total;
        return true;
    } else {
        return false;
    }
};
//点击条件查询按钮
const clickfindAll = () => {
    if (findAll(1)) {
        ElMessage.success("查询成功")
    } else {
        ElMessage.success("查询失败")
    }
}

//当实例挂载到元素之后触发onMounted
onMounted(() => {
    //1.调用方法实现，查询用户数据
    findAll(1);
})
</script>